﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;


public class SocketClient : MonoBehaviour
{   

    Socket socket;
    Text infoText;
    VideoPlayer videoPlayer;
    
    bool getData;


    void Start(){
        
    }

    public void StartClient(){
        videoPlayer=GameObject.Find("VideoPlayer").GetComponent<VideoPlayer>();
        infoText=GameObject.Find("ReceiveInfo").GetComponent<Text>();
        btn_connect_Click();
    }

   
 
    private void btn_connect_Click()
    {

        try{
            int _port =10000;
            string _ip = "127.0.0.1";

            //创建Socket客户端，获得远程ip和端号
           socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse(_ip);
            IPEndPoint point = new IPEndPoint(ip,_port);

            socket.Connect(point);
           // Debug.Log("连接成功");
            infoText.text="连接成功";

            //开启新得线程，不停接收服务器发来的消息
            Thread c_thread = new Thread(Received);
            c_thread.IsBackground = true;
            c_thread.Start();
        }catch(Exception){
            //Debug.Log("请打开服务器或IP、端口号错误...");
            infoText.text="请打开服务器或IP、端口号错误...";
        }
    }
    
    /// <summary>
    /// 接收服务端返回的消息
    /// </summary>
    void Received(){

        while(true){
            try{
                byte[] buffer = new byte[1024*1024*3];
                //实际接收的有效字数
                int len = socket.Receive(buffer);
                if(len==0){
                    break;
                }
                string str = Encoding.UTF8.GetString(buffer,0,len);
                if(str=="playVideo"&&!getData){
                    
                    videoPlayer.Play();
                    getData=true;
                }
                infoText.text="接收到： "+str + "  来自："+socket.RemoteEndPoint ;
               // Debug.Log("接收到： "+str + "  来自："socket.RemoteEndPoint ;);
                }
            catch{}
        }

    }




}
